package com.es.www.deepCopy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Serializable;

/**
 * @Created by michangtao
 * @Date 2022/5/12 16:52
 * @Description
 */
public class Person implements Cloneable, Serializable {

    private String name;

    private Integer age;

    private Phone phone;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Phone getPhone() {
        return phone;
    }

    public void setPhone(Phone phone) {
        this.phone = phone;
    }

    public Person(String name, Integer age, Phone phone) {
        this.name = name;
        this.age = age;
        this.phone = phone;
    }

    /**
     * 自定义clone方法(方式一)
     *
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person person = (Person) super.clone();
        person.setPhone((Phone) phone.clone());
        return person;
    }

    /**
     * 通过序列化方式实现深拷贝（方式二）
     *
     * @return
     */
    public Object deepClone() {
        Person person = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);//将当前对象以流的方式输出

            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            person = (Person) ois.readObject();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }

        }
        return person;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", phone=" + phone +
                '}';
    }
}
